<template>
  <div class="direct-agreenment-view view-container">

    <div class="main-content">
      <div class="list-container">

        <div
            class="filter-container"
            style="padding: 0"
        >

          <el-form
              :inline="true"
              :model="formData"
              class="filter-form-inline"
              label-position="right"
              size="small"
          >

            <el-row
                :gutter="20"
                style="margin-left: 0px; margin-right: 0px"
            >

              <el-col
                  :span="6"
              >
                <el-form-item
                    label="终端名称"
                    style="width: 100%"
                >
                  <el-input v-model="formData.terminalName"/>

                </el-form-item>
              </el-col>

              <el-col
                  :span="6"
              >
                <el-form-item
                    label="产品信息"
                    style="width: 100%"
                >
                  <el-select
                      v-model="formData.productId"
                      :loading="loading"
                      :remote-method="remoteMethod"
                      clearable
                      filterable
                      placeholder="请选择产品"
                      remote
                      reserve-keyword
                      @change="listSearch"
                  >
                    <el-option
                            v-for="item in products"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col
                  :span="6"
              >
                <el-form-item
                    label="负责营销职员"
                    style="width: 100%"
                >
                  <el-select
                      v-model="formData.headId"
                      clearable
                      placeholder="请选择职员"
                      style="width: 100%"
                      @change="listSearch"
                  >
                    <el-option
                        v-for="item in headOptions"
                        :key="item.id"
                        :label="item.realName"
                        :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col
                  :span="6"
              >
                <el-form-item style="width: 100%">
                  <el-button
                      class="border-btn"
                      @click="reset"
                  >重置
                  </el-button>
                  <el-button
                      class="main-btn"
                      type="primary"
                      @click="listSearch"
                  >搜索
                  </el-button>
                </el-form-item>
              </el-col>

              <el-col v-auth="{v:['crm:cooperation:direct:pms']}" :span="24">
                <el-button class="main-btn" size="small" style="margin-bottom: 20px" type="primary" @click="addClick">
                  新建终端直销要素
                </el-button>
              </el-col>

            </el-row>


          </el-form>

        </div>

        <table-view :cell-style="cellStyle" :data="tableData" border header-cell-class-name="table-header"
                    size="small" @row-click="rowClick">

          <el-table-column :min-width="100" :show-overflow-tooltip="true" fixed="left" header-align="center" label="编号"
                           prop="relationDevNo"/>

          <el-table-column :min-width="160" :show-overflow-tooltip="true" fixed="left" header-align="center" label="终端名称"
                           prop="terminalName"/>

          <el-table-column :min-width="100" :show-overflow-tooltip="true" header-align="center" label="所在地区">
            <template #default="{row}">
              {{ row.provinceName }}/{{ row.cityName }}/{{ row.areaName }}
            </template>
          </el-table-column>

          <el-table-column :min-width="100" :show-overflow-tooltip="true" align="center" label="终端类型"
                           prop="terminalType">
            <template #default="{row}">
              {{ getLabel('app_mode', row.terminalType) }}
            </template>
          </el-table-column>

          <el-table-column :min-width="150" :show-overflow-tooltip="true" header-align="center" label="通用名"
                           prop="productPopularName"/>

          <el-table-column :min-width="100" :show-overflow-tooltip="true" header-align="center" label="商品名"
                           prop="productName"/>

          <el-table-column :min-width="100" :show-overflow-tooltip="true" header-align="center" label="包装规格"
                           prop="packSpecs"/>

          <el-table-column :min-width="100" :show-overflow-tooltip="true" header-align="center" label="生产厂家"
                           prop="producer"/>

          <!-- <el-table-column :min-width="120" :show-overflow-tooltip="true" align="center" label="开发期限截至">
            <template #default="{row}">
              {{ dateFormat("yyyy-mm-dd", row.expireTime) }}
            </template>
          </el-table-column> -->

          <el-table-column :min-width="140" :show-overflow-tooltip="true" align="center" label="创建日期">
            <template #default="{row}">
              {{ dateFormat("yyyy-mm-dd", row.createdAt) }}
            </template>
          </el-table-column>

          <el-table-column :min-width="130" :show-overflow-tooltip="true" align="center" label="负责营销职员"
                           prop="headName"/>

          <el-table-column :min-width="150" :show-overflow-tooltip="true" align="center" fixed="right" label="状态">
            <template #default="{row}">
              <div class='tab-line'>
                <div v-if="row.flowStatus==='REPEAL' && row.processDefinitionKey == 'terminalSetAgentDirectCheck'">
                  {{ getLabel('approval_result', row.flowStatus) }}
                </div>
                <div v-else-if="row.devStatus == 1 || row.devStatus == 2 || row.devStatus == 4">
                  审核通过
                </div>
                <div v-else>
                  {{ getLabel('direct_agreement_status', row.devStatus) }}
                </div>
                <div v-if="row.flowStatus=='DOING' && row.processDefinitionKey == 'devDirectChange'"
                     class="flow-status-color">
                  [变更审核中]
                </div>
                <div
                    v-else-if="row.flowStatus==='REJECT_INITIATOR'"
                    class="flow-status-color"
                >[ {{ getLabel('approval_result', row.flowStatus) }} ]
                </div>
              </div>
              <!--                            <div style="line-height: 20px; " class="flow-status-color">-->
              <!--                                {{distributeStatus(row.distributeContractDetails)}}-->
              <!--                            </div>-->
            </template>
          </el-table-column>

          <el-table-column :min-width="100" align="center" fixed="right" label="操作">
            <template #default="{row}">

              <el-button
                      class="delete-text-btn"
                      v-auth="{v:['crm:cooperation:direct:pms'],bool:row.devStatus == -1 || row.devStatus == -2 || row.flowStatus==='REJECT_INITIATOR' || row.flowStatus==='REPEAL'}"
                  type="text" @click="onDelete(row)">
                删除
              </el-button>

              <el-button
                      v-auth="{v:['crm:cooperation:direct:pms'],bool:(row.processDefinitionKey !== 'devDirectChange' && row.devStatus != 0 && row.devStatus != -1)
                        || (row.processDefinitionKey == 'devDirectChange' && (row.flowStatus && row.flowStatus != 'DOING'))}"
                      type="text" @click="onChange(row)">
                变更
              </el-button>

            </template>

          </el-table-column>
        </table-view>

        <Pagination
            v-model:limit="formData.pageSize"
            v-model:page="formData.page"
            :total="total"
            style="display: flex; justify-content: flex-end"
            @pagination="getList"
        />

      </div>
    </div>

    <directSellingFrom ref="refDialog" @succsess-reg="listSearch"/>

    <detail-drawer
        ref="detailDrawer"
        :size-width="1000"
        custom-title
    >
      <template #title>
        <div style="display: flex;justify-content: space-between;align-items: center">
          <div>
            <span style="font-size: 14px">终端直销要素详情 - </span>
            <span>{{ datas.terminalName }}</span>
          </div>

          <div>
            <!--                        <el-button v-if="datas.devStatus == 5" class="main-btn" size="small" type="primary" @click="onChange">变更</el-button>-->
            <el-button v-auth="{v:['crm:cooperation:direct:pms'],bool:(datas.processDefinitionKey !== 'devDirectChange' && datas.devStatus != 0 && datas.devStatus != -1)
                        || (datas.processDefinitionKey == 'devDirectChange' && (datas.flowStatus && datas.flowStatus != 'DOING'))}"
                       class="main-btn" size="small" type="primary" @click="onChange(datas)">变更
            </el-button>
            <el-button
                    v-auth="{v:['crm:cooperation:direct:pms'],bool:datas.devStatus == -1 || datas.devStatus == -2 || datas.flowStatus==='REJECT_INITIATOR' || datas.flowStatus==='REPEAL'}"
                class="delete-btn" size="small" @click="onDelete(datas)">删除
            </el-button>
          </div>
        </div>

      </template>
      <template #contents>

        <item-title title="终端产品信息"/>

        <el-form
            :inline="true"
            label-position="right"
            label-width="130px"
        >

          <el-row>

            <el-col :span="8">
              <el-form-item label="编号:">
                {{ datas.relationDevNo }}
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="终端名称:">
                <el-link
                    :underline="false"
                    type="primary"
                    @click="onTerminal"
                >{{ datas.terminalName }}
                </el-link>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="所在地区:">
                {{ datas.provinceName }}/{{ datas.cityName }}/{{ datas.areaName }}
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="终端类型:">
                {{ getLabel('app_mode', datas.terminalType) }}
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="通用名:">
                {{ datas.productPopularName }}
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="商品名:">
                {{ datas.productName }}
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="包装规格:">
                {{ datas.packSpecs }}
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="生产厂家:">
                {{ datas.producer }}
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="终端价:">
                <el-link
                    :underline="false"
                    type="primary"
                    @click="onPrice"
                >{{ datas.terminalPrice }}元/{{ getLabel('sell_unit', datas.sellUnit) }}
                </el-link>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="交易价:">
                {{ datas.tradePrice }}元/{{ getLabel('sell_unit', datas.sellUnit) }}
              </el-form-item>
            </el-col>

            <!-- <el-col :span="8">
              <el-form-item label="开发期限至:">
                {{ dateFormat("yyyy-mm-dd", datas.expireTime) }}
              </el-form-item>
            </el-col> -->

            <el-col :span="8">
              <el-form-item label="创建日期:">
                {{ dateFormat("yyyy-mm-dd", datas.createdAt) }}
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="负责营销职员:">
                {{ datas.headName }}
              </el-form-item>
            </el-col>

          </el-row>

        </el-form>

        <item-title
            style="margin-top: 20px"
            title="修改记录"
        />

        <operation-view
            :id="datas.id"
            mode="dev"
        />

      </template>
    </detail-drawer>

    <!-- 产品终端价详情 -->
    <detail-drawer
        ref="detailDrawer1"
        :size-width="1000"
        custom-title
    >
      <template #title>
        <span>产品终端价 - {{ datas.priceNumber }}</span>
      </template>
      <template #contents>

        <terminalPrice :id="datas.productPriceId"/>

      </template>
    </detail-drawer>

    <detail-drawer
        ref="terminalDrawer"
        :size-width="1000"
        custom-title
    >
      <template #title>
        <span>终端 - {{ datas.terminalName }}</span>
      </template>
      <template #contents>

        <terminalInfo :id="datas.terminalId"/>

      </template>
    </detail-drawer>

    <change-dialog ref="changeDialog" @success="listSearch"/>

  </div>
</template>

<script>
  import {getProductName} from "../../../../../../../utils/commonFun";
  import {crmStore} from "../../../../../store";
import {useRouter} from 'vue-router'
import {defineAsyncComponent, defineComponent, getCurrentInstance, inject, onMounted, reactive, toRefs,} from 'vue'

export default defineComponent({
  name: 'Index',
  components: {
    changeDialog: defineAsyncComponent(
        () => import('../modules/changeDialog.vue')
    ),
    directSellingFrom: defineAsyncComponent(
        () => import('../../../modules/directSellingFrom.vue')
    ),
    terminalInfo: defineAsyncComponent(
        () => import('../../../../commonView/detailComponents/terminal/terminalInfo.vue')
    ),
    terminalPrice: defineAsyncComponent(
        () => import('../../../../commonView/detailComponents/product/terminalPrice.vue')
    )
  },
  setup() {
    const router = useRouter()
    const currentInstance = getCurrentInstance()
    const api = inject('api')
    var data = reactive({
      activeName: '1',
      datas: {},
      formData: {
        page: 1,
        pageSize: 20,
        productId: '',
        headId: '',
        terminalName: '',
        listType: '1',
        terminalListType: '2'
      },
      tableData: [],
      total: 0,
      searchStr:'',
      visible: false,
      loading: false,
      products:[],
      refDialog: null,
      headOptions: crmStore.getters['company/getHeadOptions'],
      productOptions: [],
      detailDrawer: null,
      detailDrawer1: null,
      terminalDrawer: null,
      changeDialog: null,
    })

    const handleClick = () => {
      data.tableData = []
      data.formData.page = 1
      getList()
    }

    const addClick = () => {
      data.refDialog.open()
    }

    const reset = () => {
      data.formData = {
        page: 1,
        pageSize: 20,
        productId: '',
        headId: '',
        terminalName: '',
        listType: '1',
        terminalListType: '2'
      }
      getList()
    }

    const listSearch = () => {
      data.tableData = []
      data.formData.page = 1
      getList()
    }

    const rowClick = (row, column) => {
      if (column.label === '操作') return

      data.datas = row
      data.detailDrawer.open()
    }

    const onPrice = () => {
      data.detailDrawer1.open()
    }

    const onTerminal = () => {
      data.terminalDrawer.open()
    }

    const getList = () => {
      api.terminal.PRODUCT_LIST(data.formData).then((res) => {
        if (res.code === 0) {
          data.tableData = res.data.list || [];
          data.total = res.data.total;
        }
      });
    }

    const remoteMethod = (query) => {
      data.products = []
      data.loading = true
      data.searchStr = query

      if (query) {
        const pam = {
          keyWord: query,
        }
        api.common.GET_PRODUCT_LIST(pam).then((res) => {
          if (!res.code && res.data) {
            // if (query == data.searchStr) {
            //
            // }
            res.data.list.forEach(a => {
              a.name = getProductName(a)
            })
            data.products = res.data.list

          } else {
            currentInstance.proxy.customMessage({type: 'error', message: res.msg})
          }
          data.loading = false
        })
      } else {
        data.loading = false
      }
    }

    const onDelete = (row) => {
      data.detailDrawer.close()
      currentInstance.proxy
          .alertBox({
            message: '删除数据后不可恢复，确认删除？',
            title: '删除',
          })
          .then(() => {
            api.supplyChannels.SUPPLY_CHANNELS_DELETE(row.id).then((res) => {
              if (res.code === 0) {
                currentInstance.proxy.customMessage({type: 'success', message: '删除成功'})
                getList()
              } else {
                currentInstance.proxy.customMessage({type: 'error', message: res.msg})
              }
            })
          })
          .catch((err) => {
            console.log(err)
          })
    }

    const onChange = (item) => {
      data.detailDrawer.close()
      data.changeDialog.open(item)
    }

    // 获取配送信息审核中
    const distributeStatus = (val) => {
      let a = "";
      if (val && val.length > 0) {
        for (let i = 0; i < val.length; i++) {
          if (val[i].flowStatus === "DOING") {
            a = "配送信息审核中";
            break;
          }
        }
      }
      return a;
    };

    const cellStyle = () => {
      return "cursor:pointer;";
    }

    // 获取产品下拉
    const handlProductData = async () => {
      const res = await api.terminal.TERMINAL_PRODUCTID({terminalId: 0});
      if (res.code === 0) {
        data.productOptions = res.data;
      }
    };

    onMounted(() => {
      getList()
      handlProductData()
    })

    return {
      ...toRefs(data),

      handleClick,
      addClick,
      listSearch,
      getList,
      reset,
      rowClick,
      onTerminal,
      onPrice,
      cellStyle,
      onDelete,
      distributeStatus,
      onChange,
      remoteMethod,
    }
  },
})
</script>

<style scoped>

</style>
